<template>
  <common-list class="common-list">
    <template slot="content">
      <div class="row-division-18"></div>
      <common-table v-loading="loading" :data="logList">
        <el-table-column label="日志来源" align="left" width="180px">
          <template>日志 </template>
        </el-table-column>
        <el-table-column
          label="采集时间"
          align="left"
          prop="createtime"
          width="180px"
        />
        <el-table-column label="内容" align="left" prop="content">
          <template slot-scope="scope">
            <Popover
              :label="'主机IP'"
              :type="'hostIp'"
              :isShowTootip="false"
              :typeValue="scope.row.hostIp"
            />
            <Popover
              :label="'事件类型'"
              :type="'eventType'"
              :isShowTootip="false"
              :typeValue="scope.row.eventType"
            />
            <Popover
              :label="'源IP'"
              :type="'sourceIp'"
              :isShowTootip="false"
              :typeValue="scope.row.sourceIp"
            />
            <Popover
              :label="'原始日志内容'"
              :type="'content'"
              :isShowTootip="false"
              :typeValue="scope.row.content"
            />
            <Popover
              :label="'目标IP'"
              :type="'targetIp'"
              :isShowTootip="false"
              :typeValue="scope.row.targetIp"
            />
            <Popover
              :label="'事件发生时间'"
              :type="'eventDate'"
              :isShowTootip="false"
              :typeValue="scope.row.eventDate"
            />
            <Popover
              :label="'资产类型编码'"
              :type="'softwareName'"
              :isShowTootip="false"
              :typeValue="scope.row.softwareName"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="50px">
          <template slot-scope="scope">
            <el-button type="text" @click="showDetail(scope.row)"
              >详情
            </el-button>
          </template>
        </el-table-column>
      </common-table>
    </template>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList()"
    />
    <common-info-dialog
      :infoLoading="infoLoading"
      :visible.sync="detailsOpen"
      @cancel="detailsOpen = false"
      :title="detailsTitle"
    >
      <Detail :detailForm="detailForm" v-if="isDetailForId" />
      <common-info-table v-else>
        <common-info-table-cell label="主机IP"
          >{{ detailInfo.hostIp }}
        </common-info-table-cell>
        <common-info-table-cell label="事件类型"
          >{{ detailInfo.eventType }}
        </common-info-table-cell>
        <common-info-table-cell label="源IP"
          >{{ detailInfo.sourceIp }}
        </common-info-table-cell>
        <common-info-table-cell label="原始日志内容"
          >{{ detailInfo.content }}
        </common-info-table-cell>
        <common-info-table-cell label="目标IP"
          >{{ detailInfo.targetIp }}
        </common-info-table-cell>
        <common-info-table-cell label="事件发生时间"
          >{{ detailInfo.eventDate }}
        </common-info-table-cell>
        <common-info-table-cell label="资产类型编码"
          >{{ detailInfo.softwareName }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>

    <common-edit-dialog
      :visible.sync="customOpen"
      @cancel="customOpen = false"
      @submit="customConfirm"
      :title="'自定义查询'"
    >
      <CustomFilter
        :customTreeData="customTreeData"
        :customTotalList="customTotalList"
        @getParentNodeData="getParentNodeData"
      />
    </common-edit-dialog>
    <advanced-filter
      ref="advancedFilter"
      @toSubmit="toSubmit"
    ></advanced-filter>
    <!-- 详情 -->
  </common-list>
</template>

<script>
import {
  logInfoByAlarmTargetIp,
  logDetail,
  indexExtraInfo,
  indexExtraList,
} from "@/api/alarmCenter/index";
import { PICKOPTIONS } from "@/utils/constant";
import Detail from "./Detail/index.vue";
import Popover from "./Popover";
import CustomFilter from "../../../analysisCenter/log/CustomFilter";
import AdvancedFilter from "../../../analysisCenter/log/AdvancedFilter";
import ContentTip from "../../../analysisCenter/log/ContentTip";
import { fetchCustomList, fetchEventTypes } from "@/api/analysisCenter/log";
import dayjs from "dayjs";
import {
  generateSqlString,
  generateSqlObj,
  generateTuple,
  replaceOperator,
  setOperatorList,
} from "@/utils/util";
import { deepClone } from "@/utils/index";
import { mapGetters } from "vuex";
import commonIcon from "@/components/CommonIcon";
export default {
  name: "journal",
  props: {
    params: {
      type: Object,
      default: () => {},
    },
    detail: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    Popover,
    Detail,
    CustomFilter,
    AdvancedFilter,
    commonIcon,
    ContentTip,
  },
  data() {
    return {
      customTreeData: [],
      customTotalList: [],
      customOpen: false,
      detailForm: {},
      detailsTitle: "日志详情",
      detailsOpen: false,
      infoLoading: false,
      loading: false,
      logList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: [
          new Date().getTime() - 24 * 60 * 60 * 1000,
          new Date().getTime(),
        ],
        searchContent: null,
        searchWhere: null,
      },
      pickerOptions: {
        shortcuts: PICKOPTIONS,
      },
      originContentValue: "",
      isDetailForId: false,
      detailInfo: {
        hostIp: "",
        eventType: "",
        sourceIp: "",
        content: "",
        targetIp: "",
        eventDate: "",
      },
    };
  },
  computed: {
    ...mapGetters(["systemInfo"]),
  },
  mounted() {
    // this.getLogInfoByAlarmTargetIp();
    this.getList();
    // this.getIndexExtraInfo();
    // this.getIndexExtraInfo();
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.getLogInfoByAlarmTargetIp();
      this.getList();
    },
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },

    handleInput(val) {
      if (val) {
        let valArr = val.split(" ");
        valArr.pop();
        if (valArr && valArr.length > 0) {
          this.originContentValue = valArr.join(" ");
        }
      }
    },

    handleSelect(item) {
      this.queryParams.searchContent = this.originContentValue
        ? this.originContentValue.concat(" " + item.value)
        : this.originContentValue.concat(item.value);
    },
    showCustomSearch() {
      this.customOpen = true;
      this.customTreeData = [];
      this.customTotalList = [];
      this.$store.commit("log/SET_CHECKED_CACHE_LIST", {});
      fetchCustomList({
        multiAspectStatNames:
          "eventType;hostIp;targetIp;sourceIp;eventDetailName;SubCategory;eventName;AttackName;softwareName",
      }).then((res) => {
        if (res && res.code === 200) {
          res.data.forEach((item) => {
            this.customTreeData.push(item.summaryInfo);
            this.customTotalList.push(...(item.list || []));
            this.customTotalList.forEach((item, index) => {
              item.id = item.columnName + "_" + index;
            });
          });
          this.oldTypes = deepClone(this.customTreeData);
        } else {
          this.customTreeData = [];
          this.customTotalList = [];
        }
      });
    },

    //展示高级搜索弹框
    highSearch() {
      this.$refs.advancedFilter.show();
    },

    // 高级筛选确定
    toSubmit(relations) {
      this.$refs.advancedFilter.closeDialog();
      this.queryParams.searchWhere = generateSqlObj(relations);
      this.queryParams.searchContent = replaceOperator(
        generateSqlString(relations)
      );
    },

    // 自定义查询确定
    customConfirm() {
      this.customOpen = false;
      if (this.queryParams.searchContent === null)
        this.queryParams.searchContent = "";
      console.log(this.$store.state.log.checkedCache);

      let checkedCache = this.$store.state.log.checkedCache;
      let keys = Object.keys(checkedCache);

      let values = keys.map((item) => {
        return checkedCache[item];
      });

      let result = { operate: "AND", chd: [] };
      const result2 = Object.entries(values).map(([k, v]) => {
        const chd = v.map((item) => {
          return {
            data: {
              fieldName: item.columnName,
              operator: "EQ",
              value: item.value,
            },
            operate: "OR",
          };
        });
        return {
          chd,
          operate: "OR",
        };
      });
      result.chd = result2;

      this.queryParams.searchContent = replaceOperator(
        generateSqlString(generateTuple(result), true)
      );
      this.queryParams.searchWhere = result;
    },

    getParentNodeData(val) {
      this.customTreeData = this.oldTypes.filter((item) => {
        return val
          ? item.columnAlias.toLowerCase().includes(val.toLowerCase())
          : true;
      });
    },
    // getIndexExtraInfo() {
    //   indexExtraInfo().then((res) => {});
    // },

    getList() {
      let code = this.detail.alarmCode?.slice(0, 6);

      let indexName =
        code && code === "0X0003"
          ? "index-bwda-ark-analysis-*"
          : code && code === "0X0002"
          ? "index-bwda-ark-apisecurity-*"
          : null;

      if (this.detail.processResult) {
        this.loading = true;
        let params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          indexName,
          docId: this.detail.processResult,
        };
        indexExtraList(params)
          .then((res) => {
            if (res && res.code === 200) {
              this.total = res.total;
              this.logList = res.rows;
            } else {
              this.total = 0;
              this.logList = [];
            }
          })
          .finally(() => (this.loading = false));
      } else {
        this.total = 0;
        this.logList = [];
      }
    },

    getLogInfoByAlarmTargetIp() {
      this.loading = true;
      let { targetIp } = this.params;
      let query = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        searchIndex: "index-bwda-ark-analysis-*",
      };

      query.searchWhere = this.queryParams.searchContent;
      const time =
        '(hostIp ="' +
        targetIp +
        '")' +
        " AND " +
        "createtime >=" +
        dayjs(this.queryParams.time[0]).format("YYYY-MM-DD HH:mm:ss") +
        " AND createtime <=" +
        dayjs(this.queryParams.time[1]).format("YYYY-MM-DD HH:mm:ss");
      if (query.searchWhere) {
        query.searchWhere = "(" + query.searchWhere + " AND " + time + ")";
      } else {
        query.searchWhere = "(" + time + ")";
      }
      logInfoByAlarmTargetIp(query)
        .then((res) => {
          if (res && res.code === 200) {
            this.total = res.data.total;
            this.logList = res.data.list;
          } else {
            this.total = 0;
            this.logList = [];
          }
        })
        .finally(() => (this.loading = false));
    },
    showDetail(row) {
      if (row?._index && row?._id) {
        this.infoLoading = true;
        this.isDetailForId = true;
        logDetail({ indexName: row._index, docId: row._id })
          .then((res) => {
            if (res && res.code === 200) {
              this.detailForm = res.data;
              this.detailsOpen = true;
            } else {
              this.$GlobalErrorConfirm("获取数据失败", res.msg);
            }
          })
          .finally(() => (this.infoLoading = false));
      } else {
        this.isDetailForId = false;
        Reflect.ownKeys(this.detailInfo).forEach(
          (k) => (this.detailInfo[k] = row[k])
        );
        this.detailsOpen = true;
      }
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .global-base-list-container {
  padding: 0;
}
::v-deep .common-search-wrap {
  padding: 18px 0 0 0;
}

.row-division-18 {
  height: 12px;
  background: #eee;
}
.custom-search {
  color: var(--theme-color);
  cursor: pointer;
  font-size: 14px;
}
::v-deep .list-container .global-base-list-container {
  padding-left: 18px;
}
::v-deep .list-pagination-container {
  padding-bottom: 18px;
  padding-right: 18px;
}
::v-deep .global-common-table {
  width: calc(100% - 36px) !important;
  margin: 0 18px;
}
</style>
